package com.atguigu.yygh.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.yygh.cmn.listener.DictListener;
import com.atguigu.yygh.cmn.mapper.DictMapper;
import com.atguigu.yygh.cmn.service.DictService;
import com.atguigu.yygh.model.cmn.Dict;
import com.atguigu.yygh.vo.cmn.DictEeVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName HospitalSetServiceImpl
 * @Description: 类描述
 * @Author: admin
 * @CreateDate: 2024/5/25 17:08
 * @UpdateUser: 更新人
 * @UpdateDate: 2024/5/25 17:08
 * @UpdateRemark: 更新的信息
 * @Version: 1.0
 */

@Service
@Slf4j
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict>implements DictService {

    @Autowired
    private DictMapper dictMapper;

    /**
     * 根据父id查询子节点数据
     * @param id
     * @return
     */
    @Override
    @Cacheable(value = "dict",keyGenerator = "keyGenerator")
    public List<Dict> findChildData(Long id) {
        //使用前清空wrapper,的查询条件
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", id);
        List<Dict> DList = baseMapper.selectList(wrapper);
        //设置子节点的hasChildren属性，true表示有子节点
        for (Dict dict : DList) {
            //判断是否有子节点,并设置hasChildren属性
            dict.setHasChildren(isChildren(dict.getId()));
        }
        return DList;
    }

    /**
     * 导出数据字典
     * @param response
     */
    @Override
    public void exportDictData(HttpServletResponse response) {
        try {
            //设置响应头，控制浏览器下载
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = "dict";
            fileName = URLEncoder.encode("数据字典", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");
            List<Dict> dictList = baseMapper.selectList(null);
            List<DictEeVo> dictEeVoList = new ArrayList<>();
            for (Dict dict :dictList) {
                DictEeVo dictEeVo = new DictEeVo();
                //复制属性，第一个参数是源对象，第二个参数是目标对象
                BeanUtils.copyProperties(dict,dictEeVo);
                dictEeVoList.add(dictEeVo);
            }
            //调用写操作
            EasyExcel.write(response.getOutputStream(), DictEeVo.class)
                    .sheet("dict")
                    .doWrite(dictEeVoList);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 导入数据字典
     * @param file 上传的文件
     */
    @Override
    //上传文件后，清空缓存，防止缓存数据不一致
    @CacheEvict(value = "dict", allEntries=true)
    public void importDictData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), DictEeVo.class, new DictListener(dictMapper))
                    .sheet()
                    .doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据字典编码和值获取字典名称
     * @param dictCode 字典编码
     * @param value 字典值
     * @return 字典名称
     */
    @Override
    public String getDictName(String dictCode, String value) {
//        log.info("dictCode:"+dictCode+"--------------value:"+value);
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        Dict dict =null;
        //判断是否为空，直接使用Value查询
        if(StringUtils.isEmpty(dictCode)){
//            log.info("value********************"+value);
            wrapper.eq("value", value);
        }else {
            Long parentId = getDictByCode(dictCode).getId();
//            log.info("parentId********************"+parentId);
            //因为调用了其他方法需要把wrapper清空，不然会把之前的条件带进来，如：AND (dict_code = ? AND parent_id = ? AND value = ?)
            wrapper.eq("parent_id", parentId)
                    .eq("value", value);
        }
        dict=baseMapper.selectOne(wrapper);
//        log.info("dict:{----------}"+dict);
        return dict.getName();
    }

    /**
     * 根据dictCode获取子节点数据
     * @param dictCode
     * @return
     */
    @Override
    public List<Dict> findByDictCode(String dictCode) {
        //根据dictCode获取父节点id
        Dict dict = getDictByCode(dictCode);
        //获取子节点数据
        List<Dict> childData = findChildData(dict.getId());
        return childData;
    }

    /**
     * 根据字典编码获取字典信息
     * @param dictCode 字典编码
     * @return 字典信息
     */
    private Dict getDictByCode(String dictCode) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        Dict codeDict = baseMapper.selectOne(wrapper.eq("dict_code", dictCode));
        return codeDict;
    }


    /**
     * 判断是否有子节点
     * @param id
     * @return 有值返回true,没有返回false
     */
    private boolean isChildren(Long id){
        //使用前清空wrapper,的查询条件
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", id);
        Integer count = baseMapper.selectCount(wrapper);
//        Long count = baseMapper.selectCount(wrapper);
        return count>0;
    }
}

